<template>
  <nav aria-label="Page navigation example">
    <ul class="pagination">
      <li class="page-item" :class="{ disabled: currentPage == 1 }">
        <a class="page-link" href="#" @click="changePage(1)">First</a>
      </li>

      <li class="page-item" :class="{ disabled: currentPage == 1 }">
        <a class="page-link" href="#" @click="changePage(currentPage - 1)"
          >Prev</a
        >
      </li>

      <li v-for="page in pageArray" :key="page" :class="{ active: currentPage == page }">
        <a class="page-link" href="#" @click="changePage(page)">{{ page }}</a>
      </li>

      <li class="page-item" :class="{ disabled: currentPage == lastPage }">
        <a class="page-link" href="#" @click="changePage(currentPage + 1)"
          >Next</a
        >
      </li>

      <li class="page-item" :class="{ disabled: currentPage == lastPage }">
        <a class="page-link" href="#" @click="changePage(lastPage)">Last</a>
      </li>
    </ul>
  </nav>
</template>

<script>
export default {
  props: {
    currentPage: Number,
    lastPage: Number,
    urlBase: String,
  },
  methods: {
    changePage(page) {
      this.$router.push(`${this.urlBase}${page}`);
    },
  },
  computed: {
    pageArray() {
      const NUM_PAGES = 3;

      if (this.lastPage <= NUM_PAGES) {
        // Total pages less than num, show all pages
        return Array.from({ length: this.lastPage }, (_, i) => i + 1);
      }

      let start = this.currentPage - Math.floor(NUM_PAGES / 2);
      if (start < 1) {
        start = 1;
      }

      let end = start + NUM_PAGES - 1;
      if (end > this.lastPage) {
        end = this.lastPage;
        start = end - NUM_PAGES + 1;
      }

      const pages = [];
      for (let i = start; i <= end; i++) {
        pages.push(i);
      }

      return pages;
    },
  },
};
</script>

<style>
</style>